package com.jay.tools.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.jay.tools.R;


/**
 * description: 加载更多
 * author: tjp
 * date: 2017/7/19 019 11:13
 */

public class LoadListView extends ListView implements OnScrollListener {

    private View mView;// 底部布局
    private View mFootView;

    private int mTotalItemCount;// 总数量
    private int mLastVisibleItem;// 最后一个课件的item
    private boolean mIsLoading;// 正在加载

    private ILoadListener mListener;

    public LoadListView(Context context) {
        super(context);
        initViews(context);
    }

    public LoadListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }

    public LoadListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews(context);
    }

    /**
     * 添加底部加载更多布局到ListView
     *
     * @param context
     */
    private void initViews(Context context) {
        mView = LayoutInflater.from(context).inflate(R.layout.ui_layout_list_load_more, null);
        mFootView = mView.findViewById(R.id.load_layout);

        mFootView.setVisibility(View.GONE);
        addFooterView(mView);
        setOnScrollListener(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mTotalItemCount == mLastVisibleItem && scrollState == SCROLL_STATE_IDLE) {
            if (!mIsLoading) {
                mIsLoading = true;
                mFootView.setVisibility(View.VISIBLE);
                if (mListener != null) {
                    mListener.onLoad();
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {
        mLastVisibleItem = firstVisibleItem + visibleItemCount;
        mTotalItemCount = totalItemCount;
    }

    /**
     * 加载数据完成
     */
    public void loadComplete() {
        mIsLoading = false;
        mFootView.setVisibility(View.GONE);
    }

    public void setILoadListener(ILoadListener listener) {
        mListener = listener;
    }

    public interface ILoadListener {
        /**
         * 加载数据
         */
        void onLoad();
    }

}
